﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using NLog;
using DeSleeper.Service;

namespace DeSleeper.ServiceHost
{
	public partial class WakeOnLanProxyService : ServiceBase
	{
		private static readonly Logger logger = LogManager.GetCurrentClassLogger();

		public static ManualResetEvent _pause = new ManualResetEvent(false);
		private System.ServiceModel.ServiceHost _serviceHost;

		public WakeOnLanProxyService()
		{
			InitializeComponent();
		}

		protected override void OnStart(string[] args)
		{
			try
			{
				_serviceHost = new System.ServiceModel.ServiceHost(typeof(WakeUpService));
				_serviceHost.Open();
				try
				{
					if (ProxyRegister.IsConfigured())
						ProxyRegister.StartLocally();
				}
				catch (Exception e)
				{
					logger.ErrorException("Failure starting proxy register service (WakeUp Service is running): ", e);
				}
			}
			catch (Exception e)
			{
				logger.ErrorException("Failure starting service: ", e);
				throw;
			}
		}

		protected override void OnStop()
		{
			try
			{
				if (_serviceHost != null && _serviceHost.State == CommunicationState.Opened)
					_serviceHost.Close();
				ProxyRegister.Stop();
			}
			catch (Exception e)
			{
				logger.ErrorException("Failure stopping service: ", e);
				throw;
			}
		}
	}
}
